package cn.org.qary.controller.qhn.front;

import cn.org.qary.entity.FirstType;
import cn.org.qary.entity.SecondaryType;

import cn.org.qary.service.trait.yaokaiing.FirstTypeService;
import cn.org.qary.service.trait.yaokaiing.SecondaryTypeService;
import io.vavr.Tuple2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 一级分类二级分类的控制层
 */
@Controller
@RequestMapping("type")
public class TypeController {

    @Autowired
    FirstTypeService firstTypeService;

    @Autowired
    SecondaryTypeService secondaryTypeService;

    /**
     * 根据一级分类查询二级分类
     * @param model
     * @return
     */
    @RequestMapping("init")
    public String init(Model model){
        Map<FirstType, List<SecondaryType>> map =
                firstTypeService.selectAll()
                .stream()
                .map(f -> {
                    Example example = new Example(SecondaryType.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andEqualTo("firstTypeId", f.getId());
                    return new Tuple2<>(f, secondaryTypeService.selectByCondition(example));
                })
                .collect(Collectors.toMap(t -> t._1(), t -> t._2()));
// 与上面的代码等价
//        List<FirstType> firstTypeList = firstTypeService.selectAll();
//        Map<FirstType, List<SecondaryType>> map = new HashMap<>();
//        for (FirstType firstType : firstTypeList) {
//            Example example = new Example(SecondaryType.class);
//            Example.Criteria criteria = example.createCriteria();
//            criteria.andEqualTo("firstTypeId", firstType.getId());
//
//            List<SecondaryType> secondaryTypeList = secondaryTypeService.selectByCondition(example);
//            map.put(firstType, secondaryTypeList);
//        }
        model.addAttribute("map", map);
        //TODO: 写跳转到哪个页面
        return "index";
    }
}
